package com.wujilin.okra.fragment;

import static com.wujilin.okra.Okra.FORMATTER_DATE_TIME;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_CONTENT;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_ID;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_TIME;

import org.joda.time.DateTime;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.wujilin.okra.R;
import com.wujilin.okra.database.Sql;

public class ObjectiveEditFragment extends DialogFragment implements OnClickListener {
	private EditText contentEdit;
	
	public static ObjectiveEditFragment newInstance(long objectiveId, String objectiveContent) {
		Bundle args = new Bundle(2);
		args.putLong(EXTRA_OBJECTIVE_ID, objectiveId);
		args.putString(EXTRA_OBJECTIVE_CONTENT, objectiveContent);
		
		ObjectiveEditFragment fragment = new ObjectiveEditFragment();
		fragment.setArguments(args);
		
		return fragment;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_objective, null);
		
		String content = getArguments().getString(EXTRA_OBJECTIVE_CONTENT);
		
		contentEdit = (EditText) view.findViewById(R.id.objective_content);
		contentEdit.setText(content);
		contentEdit.setSelection(content.length());
		
		Dialog dialog = new AlertDialog.Builder(getActivity())
				.setTitle(R.string.edit_objective)
				.setView(view)
				.setPositiveButton(android.R.string.ok, this)
				.setNegativeButton(android.R.string.cancel, null)
				.create();
		
		return dialog;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (which == DialogInterface.BUTTON_POSITIVE) {
			String content = contentEdit.getText().toString();
			long id = getArguments().getLong(EXTRA_OBJECTIVE_ID, 0);
			String time = DateTime.now().toString(FORMATTER_DATE_TIME);
			Sql.update("objective", id, "content", content, "time", time);
			Intent data = new Intent();
			data.putExtra(EXTRA_OBJECTIVE_CONTENT, content);
			data.putExtra(EXTRA_OBJECTIVE_TIME, time);
			getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, data);
		}
	}
}